<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/12
 * Time: 下午4:54
 */

namespace app\api\repository;

use app\common\Model\Order;
use app\common\Model\UserBalance;
use app\common\Model\UserShaohuo;
use app\common\Service;
use think\Db;

class UserBalanceRespository extends Service
{
    /**
     * 提现
     * @param $uid
     * @param $amount
     * @param $zfbaccount
     * @param $realname
     */
    public function withdraw($uid, $amount, $zfbaccount, $realname)
    {
        if ($uid == '') {
            return [
                'code' => 'fail',
                'msg' => '用户ID不能为空'
            ];
        }

        if (trim($amount) == '') {
            return [
                'code' => 'fail',
                'msg' => '提现金额不能为空'
            ];
        }

        if (trim($zfbaccount) == '') {
            return [
                'code' => 'fail',
                'msg' => '支付宝账户不能为空'
            ];
        }

        if (trim($realname) == '') {
            return [
                'code' => 'fail',
                'msg' => '用户姓名不能为空'
            ];
        }

        $isExist = Db::table('sh_withdraw_log')
            ->where(['uid' => $uid, 'status' => 0])
            ->find();

        if ($isExist) {
            return [
                'code' => 'fail',
                'msg' => '用户有正在提现的记录，请等待'
            ];
        }
        //检测用户是否可以提现
        /*$user = Db::table('sh_user_shaohuo ushaohuo')
            ->join('sh_user_balance balance', 'ushaohuo.uid=balance.uid')
            ->where('ushaohuo.uid', $uid)
            ->where('ushaohuo.status', UserShaohuo::STATUS_NORMAL)
            ->find();

        if (empty($user)) {
            return [
                'code' => 'fail',
                'msg' => '只有捎货人才能提现'
            ];
        }*/

        $user = Db::table('sh_user_balance')->where('uid', $uid)->find();

        //提现余额单位转换
        $amount = $amount * config('convert_unit');

        //检测用户申请余额是否足够提现
        if ($user['withdraw_balance'] < $amount) {
            return [
                'code' => 'fail',
                'msg' => '可提现余额不足'
            ];
        }

        Db::startTrans();
        try {

            //创建Pay_log日志
            $res = PayLogRespository::instance()->createPayLog(
                $uid,
                Order::createOrderNum(Order::WD),
                2,
                3,
                0,
                $amount // 单位为分
            );

            if (!isset($res['order_num'])) {
                Db::rollback();
                return [
                    'code' => 'fail',
                    'msg' => '创建日志失败'
                ];
            }

            //创建提现记录
            $log = WithdrawLogRespository::instance()->createDrawLog($uid, $zfbaccount, $realname, $amount,$res['order_num']);

            //用户的提现余额转入冻结金额
            $model = model('app\common\Model\UserBalance');
            $model->where('uid', $uid);
            $model->withdraw_balance = $user['withdraw_balance'] - $amount;
            $model->frozen_balance = $amount;
            $model->isUpdate(true)->save();
            Db::commit();
            return [
                'code' => 'success',
                'msg' => '提现请求已提交'
            ];
        } catch (\Exception $e) {
            Db::rollback();
            return [
                'code' => 'fail',
                'msg' => $e->getMessage()
            ];
        };

    }

    /**
     * 添加捎货人的收益
     * @param $uid
     * @param $orderId 订单号
     */
    public static function addShipperIncome($uid, $orderId)
    {
        if ($uid == '') {
            return [
                'code' => 'fail',
                'msg' => '用户ID不能为空'
            ];
        }

        if (trim($orderId) == '') {
            return [
                'code' => 'fail',
                'msg' => '订单不能为空'
            ];
        }

        $user_wallet = Db::table('sh_user_balance')->where('uid', $uid)->find();

        /**
         * 钱包为空 创建钱包
         */
        if ($user_wallet == null) {
            $user_wallet = UserBalance::createUserWallet($uid);
        }


        //查询用户的订单信息
        $orderinfo = Order::getOrderInfoByOrderNumOrId('', $orderId);

        if ($orderinfo['code'] != 'success') {
            return [
                'code' => 'fail',
                'msg' => $orderinfo['msg'],
            ];
        }

        //订单状态判断
        if ($orderinfo['data']['status'] != '5') {
            return [
                'code' => 'fail',
                'msg' => '当前状态不可操作status：' . $orderinfo['data']['status'],
            ];
        }

        //更新用户钱包信息
        $model = model("app\common\Model\UserBalance");
        $model->where('uid', $uid);
        $model->withdraw_balance = $user_wallet['withdraw_balance'] + $orderinfo['data']['shipping_fee'] * config('divide_rate');
        WLog('aaaaaaa.txt',$user_wallet['withdraw_balance'] + $orderinfo['data']['shipping_fee'] * config('divide_rate'));
        if ($model->isUpdate(true)->save()) {
            //创建Pay_log日志
            $paylogs = PayLogRespository::instance()->createPayLog(
                $uid,
                $orderinfo['data']['order_num'],
                2,
                4,
                0,
                $orderinfo['data']['shipping_fee'] * config('divide_rate'), // 单位为分
                1
            );

            //记录本地收益
            $info['uid'] = $uid;
            $info['order_id'] = $orderId;
            $info['type'] = '捎货人收益';
            WLog('income.txt', json_encode($info));
            return [
                'code' => 'success',
                'msg' => '收益增加成功'
            ];
        }
        return [
            'code' => 'success',
            'msg' => $model->getError()
        ];
    }
}